<template>
    <view class="chat-input">
        <view class="chat-input__content">
            <view :scroll-y="true" class="chat-input__box">
                <textarea ref="textareaRef" v-model="content" type="textarea" class="chat-input__box__textarea" :focus="focus" :maxlength="maxLength"
                    :adjust-position="false" :auto-height="true" @confirm="send" @focus="onFocus" @blur="onBlur" @keyboardheightchange="onKeyboardheightchange" />
            </view>
            <view class="chat-input__menu">
                <u-icon class="chat-input__menu__emoji" name="pause-circle-fill" color="#2979ff" size="60rpx"
                    @click="openTool(0)"></u-icon>
                <u-icon class="chat-input__menu__add" name="plus-circle-fill" color="#2979ff" size="60rpx"
                    @click="openTool(1)"></u-icon>
                <!-- <text class="chat-input__menu__emoji iconfont" >&#xe622;</text> -->
                <!-- <text class="chat-input__menu__add iconfont" @click="openTool(1)">&#xe68f;</text> -->
                <!-- #ifdef H5 -->
                <button v-show="content" class="chat-input__menu__btn" @click.prevent="send">
                    <text class="chat-input__menu__btn__text">发送</text>
                </button>
                <!-- #endif -->
                <!-- #ifndef H5 -->
                <button v-if="content" class="chat-input__menu__btn" @touchend.prevent="send">
                    <text class="chat-input__menu__btn__text">发送</text>
                </button>
                <!-- #endif -->
            </view>
        </view>
        <swiper v-if="showTool" ref="tools" :style="{height: keyBoarHeight + 'px'}" :current="current" duration="200">
            <swiper-item>
                <emoji-list v-if="tapShowTool" @change="insertEmoji"></emoji-list>
            </swiper-item>
            <swiper-item>
                <more-list v-if="tapShowTool" :type="type" @change="handlerMore"></more-list>
            </swiper-item>
        </swiper>
        <aite-friend v-if="showAite" ref="aite-friend" @change="addContent">
        </aite-friend>
    </view>
</template>
<script>
    import emojiList from './emoji-list.vue'
    import moreList from './more-list.vue'
    import aiteFriend from './aite-friend.vue'
    // #ifdef APP-NVUE
    const animation = uni.requireNativePlugin('animation')
    // #endif
    // import {
    //     chatInputNotSent
    // } from '@/common/storageSync.js'
    /**
     * 聊天输入框
     * @author liruilin
     */
    export default {
        name: 'chat-input',
        components: {
            emojiList,
            moreList,
            aiteFriend
        },
        props: {
            maxLength: {
                type: [Number],
                default: 50
            },
            // isOnKeyboard: {
            //     type: Boolean,
            //     default: false
            // },
            type: {
                type: String,
                default: 'group'
            }
        },
        data() {
            return {
                current: 0,
                content: '',
                keyBoarHeight: 0,
                isKeyWord: false,
                showTool: false, //控制工具栏显示和隐藏
                tapShowTool: false, // 用户主动操作显示工具栏的状态，用来键盘隐藏后判断需不需要隐藏工具栏
                thisInput: false,
                focus: false,
                uniteUserId: []
            }
        },
        computed: {
            showAite() {
                return this.type == 'group' || this.type == 'server'
            }
        },
        watch: {
            content(nVal, oVal) {
                // 打开@好友
                if (this.showAite && nVal.length > oVal.length && nVal.substr(nVal.length - 1, 1) == '@') {
                    this.$refs['aite-friend'].open()
                }
                this.$emit('input', nVal)
            },
            showTool(state){
                this.$emit('onTurn', state)
            }
        },
        created() {
            this.init()
            this.keyBoarHeight = uni.getStorageSync('keyBoarHeight') || 240
        },
        methods: {
            init() {
                
            },
            onKeyboardheightchange(event) {
                // #ifdef APP-PLUS || MP-WEIXIN
                let {duration,height } = event.detail
                //监听键盘弹起获取键盘高度，给功能区设置高度
                if (height > 0 ) { //键盘弹出
                    let keyBoarHeight = height - this.getSafeAreaInsets().deviceBottom
                    this.keyBoarHeight = keyBoarHeight
                    uni.setStorageSync('keyBoarHeight', keyBoarHeight)
                    this.isKeyWord = true
                    this.showTool = true
                } else { //键盘隐藏
                    this.isKeyWord = false
                    if(!this.tapShowTool) this.showTool = false
                    this.textareaBlur()
                }
                // #endif
            },
            // 发送输入框基本消息
            send() {
                if (!this.content) return
                // this.tapShowTool = false
                this.$emit('send', {
                    type: this.type,
                    message: this.linkEscape( this.uniteEscape(this.content) ),
                    // @人员id
                    uniteUserId: this.uniteUserId.length ? this.uniteUserId : null,
                })
                this.content = ''
                this.uniteUserId = []
                // this.closeToolsBoxAndKeyboard()
            },
            /**
             * 添加消息
             * focus 是否获取焦点
             * empty 是否清空
             */
            addContent({
                content = '',
                focus = false,
                empty = false,
            } = {}) {
                if(empty){
                    this.content = content
                }else{
                    this.content += content
                }
                if(focus) this.textareaFocus()
            },
            // @信息转义
            uniteEscape(message) {
                let _IsText = message || ''
                if (message.indexOf(`@`) != -1) {
                    let NicknamesList = [],
                        NicknamesObject = {}
                    Array.from(this.existUniteList || [], User => {
                        NicknamesObject[`@${User.name}`] = User
                        message.indexOf(`@${User.name}`) != -1 ? NicknamesList.push(`@${User.name}`) :
                            ''
                    })
                    _IsText.replace(/@\.[\s\S]+?\./g, (str) => {
                        let IsStr = (str.match(/@\.([\s\S]+?)\./) || [])[1],
                            IsCursor = _IsText.indexOf(`${str}`)
                        _IsText = _IsText.slice(0, IsCursor) + _IsText.slice(IsCursor + str.length)
                    })
                    Array.from(NicknamesList || [], point => {
                        this.uniteUserId.push(`${NicknamesObject[point].user_id}`)
                        let IsCursor = _IsText.indexOf(`${point}`),
                            IsLimit = `unite(${NicknamesObject[point].user_id}_${NicknamesObject[point].name})`
                        _IsText = _IsText.slice(0, IsCursor) + IsLimit + _IsText.slice(IsCursor + point.length)
                    })
                }
                return _IsText
            },
            // 转义文本中带的链接
            linkEscape(message){
                return message.replace(/(https?|http|ftp|file:\/\/)([-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])/gi, `a($1$2)[$1$2]`)
            },
            //获取安全区高度，ios
            getSafeAreaInsets() {
                // #ifdef APP-PLUS
                return plus.navigator.getSafeAreaInsets()
                // #endif
                // #ifndef APP-PLUS
                return {
                    deviceBottom: 0
                }
                // #endif
            },
            // 失去焦点触发
            textareaBlur() {
                this.focus = false
                this.$refs.textareaRef && this.$refs.textareaRef.blur && this.$refs.textareaRef.blur()
            },
            // 输入框主动获焦
            textareaFocus() {
                this.focus = true
                this.$refs.textareaRef && this.$refs.textareaRef.focus && this.$refs.textareaRef.focus()
            },
            onFocus(){
                this.tapShowTool = false
                this.thisInput = true
                // #ifdef H5
                if(this.showTool){
                    this.openTool(this.current)
                }
                // #endif
            },
            onBlur(){
                this.thisInput = false
            },
            openTool(index) {
                this.tapShowTool = true
                // #ifdef APP-PLUS || MP-WEIXIN
                this.showTool = true
                // #endif
                // #ifndef APP-PLUS
                if(index === this.current){ 
                    this.showTool = !this.showTool
                }
                // #endif
                this.$nextTick(function() {
                    this.current = index
                })
                if (this.keyBoarHeight) {
                    this.textareaBlur()
                }
            },
            // 关闭输入状态
            closeToolsBoxAndKeyboard() {
                this.showTool = false
                this.tapShowTool = false
                this.textareaBlur()
            },
            //输入表情
            insertEmoji(str) {
                this.content += str 
            },
            handlerMore(type) {
                switch (type) {
                    // 选择发送图片
                    case 'images':
					uni.chooseImage({
						count: 9,
						success: (res) => {
							this.$emit('send', {
							    message: ``,
								images: res.tempFilePaths
							})
						}
					})
                        
                    break
                }
            },
            // 发送反馈联想
            sendFeedbackLenovo(data) {
                this.$emit('send', {
                    message: `associate(${data.content})[work_${data.title}_${data.id}]`
                })
            }
        }
    }
</script>

<style scoped lang="scss">
    .chat-input {
        padding-left: 15rpx;
        padding-top: 10rpx;
        padding-bottom: 20rpx;
        padding-right: 15rpx; 
        &__content {
            display: flex;
            flex-direction: row;
            align-items: flex-end;
        }

        &__box {
            display: flex;
            flex: 1;
            width: 0;
            flex-direction: row; 
            padding-top: 15rpx;
            padding-bottom: 18rpx;
            padding-left: 15rpx;
            padding-right: 15rpx;
            background-color: #FFFFFF;
            border-radius: 7rpx;
            &__textarea {
                max-height: 196rpx;
                padding-top: 5rpx; 
                flex: 1;
                font-size: 30rpx;
                line-height: 50rpx;
            }
        }
        &__menu {
            display: flex;
            height: 76rpx;
            flex-direction: row;
            align-items: center;

            &__emoji {
                font-size: 60rpx;
                margin-left: 10rpx;
                color: #cdcac7;
            }

            &__add {
                font-size: 60rpx;
                margin-left: 10rpx;
                color: #cdcac7;
            }

            &__thing {
                margin-left: 10rpx;
            }

            &__btn {
                margin-left: 10rpx;
                padding-left: 25rpx;
                padding-right: 25rpx;
                padding-top: 15rpx;
                padding-bottom: 15rpx;
                background-color: #07bf60;
                border-radius: 10rpx;
                border: none;
                line-height: 40rpx;
                &__text{
                    line-height: 40rpx;
                    font-size: 30rpx;
                    color: #FFFFFF;
                }
            }
        }
    }
</style>
